'use strict';

define(function(require, exports, module) {
    var angular = require('angular');
    var dialog = require('@yunke/art-dialog').default;
    require('../../../public/js/plugins/select2/select2');
    var util = require('@yunke/core/util').default;
    var ui = require('@yunke/core/ui');
    var api_prefix = G_CONFIG['api_prefix']; //api前缀
    require('../../../public/js/myservice/contract/contract-common');
    var config = require('../../../public/js/myservice/config');
    var _ = require('lodash');
    var myMath = require('../../../public/js/myservice/common/my-math');

    var ContractReceivableInvoice = angular.module('ContractReceivableInvoice', ['ContractCommonService']);

    ContractReceivableInvoice.filter('signOrIncomeAmount', function() {
        return function(contract) {
            //云客签约-直属区域/云客签约-联营区域/云客直销
            //使用签约金额
            var limitContractArr = ['7f83719a-fce8-11e4-bed8-00155d02c832', '7f8422d0-fce8-11e4-bed8-00155d02c832', 'efa353cd-51ca-11e8-a035-00155d02c83e'];
            if (contract.contract_property_id == limitContractArr[0] ||
                contract.contract_property_id == limitContractArr[1] ||
                contract.contract_property_id == limitContractArr[2]) {
                return contract.sign_amount;
            } else {
                return contract.income_amount ? contract.income_amount : 0;
            }
        };
    }).filter('sumInvoiceAmount', function() {
        return function(invoices) {
            var amount = 0;
            if (invoices) {
                $.each(invoices, function(i, d) {
                    if (d.__type == 'delete') {
                        return;
                    }
                    amount = myMath.add(amount, d.invoice_amount);
                });
            }

            return amount;
        };

    }).filter('remainInvoiceAmount', function() {
        return function(invoices, contract) {
            var amount = 0;
            if (invoices) {
                $.each(invoices, function(i, d) {
                    if (d['__type'] == 'delete') {
                        return;
                    }
                    amount = myMath.add(amount, parseFloat(d.invoice_amount));
                });
            }

            var limitContractArr = ['7f83719a-fce8-11e4-bed8-00155d02c832', '7f8422d0-fce8-11e4-bed8-00155d02c832', 'efa353cd-51ca-11e8-a035-00155d02c83e'];
            if (contract.contract_property_id == limitContractArr[0] ||
                contract.contract_property_id == limitContractArr[1] ||
                contract.contract_property_id == limitContractArr[2]) {
                return myMath.sub(contract.sign_amount, amount);
            } else {
                return myMath.sub(contract.income_amount, amount);
            }

            return 0;
        };
    }).service('receivableInvoiceService', [
        '$rootScope', '$filter', 'contractCommonService', function($rootScope, $filter, contractCommonService) {
            $rootScope.invoiceInfo = {};
            $rootScope.editFunds = [];

            var service = {
                onCloseInvoice($dialogScope, invoiceType) {
                    if ($dialogScope.saveAndAdd === true) {
                        if (invoiceType === 1) {
                            $('#addVoiceButton').trigger('click');
                        }
                        if (invoiceType === 2) {
                            $('#addMainVoiceButton').trigger('click');
                        }
                    }
                },
                addAndSaveBtn($dialog, $dialogScope) {
                    $($dialog.node).
                        find('[i-id=ok]').
                        after(
                            '<button type="button" i-id="okAdd" class="ui-dialog-autofocus" onclick="">确定并新增</button>');
                    $($dialog.node).find('[i-id=okAdd]').on('click', function() {
                        $dialogScope.saveAndAdd = true;
                        $($dialog.node).find('[i-id=ok]').trigger('click');
                    });
                    $($dialog.node).find('[i-id=cancel]').on('click', function() {
                        $dialogScope.saveAndAdd = false;
                    });
                },
                onInvoiceEditShow(
                    $data, $dialog, $dialogScope, invoiceType, oldInvoice, contract, invoiceData) {
                    /**
                     * 打开发票编辑界面时初始化
                     * invoiceType: 发票类型：1：发票，2：子发票，3：红冲发票，4：收据 {number}
                     * oldInvoice: 原发票
                     * contract : 合同基本信息 {object}
                     * invoiceData : 合同发票已录入数据 {array}
                     */

                    var now = new Date(),
                        now_y = now.getFullYear(),
                        now_m = now.getMonth() + 1,
                        now_M = (now_m > 9) ? now_m : ('0' + now_m),
                        now_d = now.getDate(),
                        now_D = (now_d > 9) ? now_d : ('0' + now_d),
                        format_now = now_y + '-' + now_M + '-' + now_D;

                    if (!oldInvoice) {
                        setTimeout(function() {
                            //默认设置发票类型为服务票
                            $('#category').data('select2').updateSelection({id: 1, text: '服务票'});
                            $dialogScope.invoiceInfo.invoice_category = 1;
                            $('#idInvoiceCompany').data('select2').updateSelection({
                                id: 'f775a92e-0071-11e5-bed8-00155d02c832',
                                text: '明源云客'
                            });
                            $dialogScope.invoiceInfo.invoice_company_id = 'f775a92e-0071-11e5-bed8-00155d02c832';
                            $dialogScope.invoiceInfo.invoice_date = format_now;
                        }, 0);

                    }

                    //如果合同类型为 “联营签约-云客结算” 设置默认值
                    $dialogScope.requiredProposer = 0;
                    if (contract.contract_property_id == '7f856e81-fce8-11e4-bed8-00155d02c832' && oldInvoice == null) {
                        setTimeout(function() {
                            //客户名称
                            $dialogScope.invoiceInfo.customer_name = contract.company_name;
                            //开票单位
                            $('#idInvoiceCompany').data('select2').updateSelection({
                                id: 'f775a92e-0071-11e5-bed8-00155d02c832',
                                text: '明源云客'
                            });
                            $dialogScope.invoiceInfo.invoice_company_id = 'f775a92e-0071-11e5-bed8-00155d02c832';
                            //开票时间
                            $dialogScope.invoiceInfo.invoice_date = format_now;
                            //开票金额
                            $dialogScope.invoiceInfo.invoice_amount = contract.income_amount;
                            //声请人是否必须
                            $dialogScope.requiredProposer = 0;
                        }, 0);
                    }

                    if (invoiceType == 1 || invoiceType == 4) {
                        $dialogScope.maxInvoiceAmount = $filter('remainInvoiceAmount')(invoiceData, contract);
                    }

                    if (invoiceType === 1) {
                        this.addAndSaveBtn($dialog, $dialogScope);
                    }

                    //新建发票
                    $dialogScope.invoiceInfo = {
                        invoiceSummarys: [],
                        invoiceDocuments: [],
                        contract_id: $data,
                        is_receipt: invoiceType == 4 ? 1 : 0,
                        is_red_invoice: invoiceType == 3 ? 1 : 0,
                        is_child_invoice: invoiceType == 2 ? 1 : 0,
                        is_main_invoice: 0
                    };

                    //开票金额变更时，重新计算分摊金额
                    $dialogScope.$watch('invoiceInfo.invoice_amount', function() {
                        $dialogScope.shareAmount();
                    });

                    //分摊发票金额
                    $dialogScope.shareAmount = function() {

                        const items = $dialogScope.editInvoiceReceivables || [];
                        //
                        let invoiceAmount = ($dialogScope.invoiceInfo.invoice_amount || 0) -
                            ($dialogScope.invoiceInfo.receivables_amount || 0);

                        // 正常发票
                        if ($dialogScope.invoiceInfo.is_red_invoice == '0') {
                            _.each(items, function(item) {
                                // 未选中的款项或者是发票金额小于等于0，将该款项的本次开票金额为置为0
                                if (!item._checked || invoiceAmount <= 0) {
                                    item.cur_billing_amount = 0;
                                    return true;
                                }
                                // 本次开票金额  应收金额 - 已开票金额
                                item.cur_billing_amount = myMath.sub(item.receivable_amount, item.billing_amount);
                                invoiceAmount -= item.cur_billing_amount;
                                if (invoiceAmount < 0) {
                                    item.cur_billing_amount += invoiceAmount;
                                }
                            });
                        } else if ($dialogScope.invoiceInfo.is_red_invoice == '1') {
                            //红冲发票 本次开票金额是负数， 已开票相应减少
                            _.each(items, function(item) {

                                const checkedCal = x => {
                                    item.billing_amount = myMath.add(item.billing_amount, x);
                                    item.cur_billing_amount = myMath.add(item.cur_billing_amount, x);
                                };

                                const uncheckedCal = x => {
                                    item.billing_amount = myMath.sub(item.billing_amount, x);
                                    item.cur_billing_amount = myMath.sub(item.cur_billing_amount, x);
                                };

                                if (!item._checked) {
                                    uncheckedCal(item.cur_billing_amount);
                                    return true;
                                }

                                if (item.cur_billing_amount < 0) {
                                    uncheckedCal(item.cur_billing_amount);
                                }

                                if (myMath.add(item.billing_amount, invoiceAmount) <= 0) {
                                    invoiceAmount = myMath.sub(invoiceAmount, myMath.sub(0, item.billing_amount));
                                    checkedCal(myMath.sub(item.cur_billing_amount, item.billing_amount));
                                } else {
                                    checkedCal(myMath.add(item.cur_billing_amount, invoiceAmount));
                                    invoiceAmount = myMath.sub(invoiceAmount, invoiceAmount);
                                }

                            });
                        }

                    };

                    $dialogScope.orgianlInvoice = oldInvoice;
                    $dialogScope.invoiceType = invoiceType;
                    $dialogScope.invoiceName = invoiceType == 4 ? '收据' : '发票';

                    //下拉框设置
                    //发票类别
                    $dialogScope.ddlConfigInvoiceCategory = {
                        allowClear: false,
                        data: [{id: 1, text: '服务票'}, {id: 0, text: '销售票'}],
                        minimumResultsForSearch: 'Infinity'

                    };

                    //发票类型
                    $dialogScope.ddlConfigInvoiceType = {
                        allowClear: false,
                        data: [{id: '0', text: '增值税普通发票'}, {id: '1', text: '增值税专用发票'}],
                        minimumResultsForSearch: 'Infinity'
                    };

                    //摘要类型
                    $dialogScope.ddlConfigInvoiceSummaryType = {
                        allowClear: false,
                        data: _.map(
                            ['软件技术服务费', '软件服务费', '服务费', '明源云客电子商务平台－移动销售系统V1.0', '明源云客来访登记系统V1.0', '广告费', '广告发布费'],
                            x => ({
                                id: x,
                                text: x
                            })),
                        minimumResultsForSearch: 'Infinity'
                    };

                    //申请人
                    $dialogScope.ddlConfigInvoiceProposer = {
                        allowClear: false,
                        ajax: {
                            url: api_prefix + 'erp-interface/get-users',
                            dataType: 'json',
                            delay: 250,
                            data(term) {
                                return {
                                    keyword: term,
                                    limit: 10
                                };
                            },
                            results(json, page) {
                                var data = [];
                                if (json.retCode === '0') {
                                    data = json.data;
                                }
                                return {results: data};
                            },
                            cache: true
                        },
                        escapeMarkup(markup) {
                            return markup;
                        }, // let our custom formatter work
                        minimumInputLength: 1,
                        onchange2(newVal) {
                            $dialogScope.invoiceInfo.user_name = newVal.UserName;
                            $dialogScope.invoiceInfo.area_name = newVal.BUName;
                        }
                    };
                    //开票单位
                    $dialogScope.ddlConfigInvoiceCompany = {
                        allowClear: false,
                        data: [],
                        onchange2(newVal) {
                            $dialogScope.invoiceInfo.invoice_company_name = newVal.BUName;
                        }
                    };

                    contractCommonService.getInvoiceBusinessUnit(function(data) {
                        var ddlData = [];
                        $.each(data, function(i, d) {
                            //只显示明源云客
                            if (d.BUGUID == 'f775a92e-0071-11e5-bed8-00155d02c832') {
                                ddlData.push({id: d.BUGUID, text: d.BUName});
                            }

                        });
                        $dialogScope.ddlConfigInvoiceCompany.data = ddlData;
                        $dialogScope.$applyAsync();
                    });

                    //主发票ddl
                    $dialogScope.ddlConfigMainInvoice = {
                        ajax: {
                            url: api_prefix + 'receivable/get-parent-invoice-info',
                            dataType: 'json',
                            delay: 250,
                            data(term, page) {
                                return {
                                    keyword: term, // search term
                                    page: page
                                };
                            },
                            results(json, page) {
                                var data = [];
                                if (json.retCode == 0) {
                                    data = json.data;
                                    $.each(data, function(i, d) {
                                        d.id = d.invoice_id;
                                        d.text = d.invoice_no;
                                    });
                                }
                                return {results: data};
                            },
                            cache: true
                        },
                        minimumInputLength: 1
                    };

                    if (oldInvoice) {
                        $dialogScope.invoiceInfo = angular.extend({}, oldInvoice);
                        setTimeout(function() {
                            $('.idProposer:last').data('select2').updateSelection({text: oldInvoice.UserName || ''});
                        }, 500);
                    }

                    //获取应收信息列表
                    if (invoiceType != 3) {
                        //非红冲发票去应收信息
                        contractCommonService.getContractReceivable($data, function(json) {
                            json.forEach(function(v) {
                                v.cur_billing_amount = 0;
                            });
                            $dialogScope.editInvoiceReceivables = json;
                            $dialogScope.$applyAsync();
                        });
                    } else {
                        $dialogScope.invoiceInfo.red_by_invoice_id = $dialogScope.invoiceInfo.invoice_id;
                        $dialogScope.invoiceInfo.invoice_id = null;//红冲发票新增记录
                        $dialogScope.invoiceInfo.is_red_invoice = 1;
                        $dialogScope.invoiceInfo.invoice_amount = -$dialogScope.invoiceInfo.invoice_amount;
                        setTimeout(function() {
                            $('.idInvoiceCompany:last').
                                data('select2').
                                updateSelection({text: oldInvoice.BUName || ''});
                            $('.idMainInvoice:visible').length && $('.idMainInvoice:visible').
                                data('select2').
                                updateSelection({text: oldInvoice.main_invoice_no});
                        }, 500);

                        $.each($dialogScope.invoiceInfo.invoiceSummarys, function(i, d) {
                            d.summary_amount = -Math.abs(d.summary_amount);
                        });
                    }

                    $dialogScope.totalEqualAmount = function() {
                        if ($dialogScope.invoiceInfo.invoice_amount) {
                            return $dialogScope.totalAmount() != $dialogScope.invoiceInfo.invoice_amount;
                        } else {
                            return false;
                        }
                    };

                    /**
                     * 计算摘要金额总和
                     * @returns {number}
                     */
                    $dialogScope.totalAmount = function() {
                        var sum = 0;

                        var items = $dialogScope.invoiceInfo.invoiceSummarys;
                        if (items) {
                            for (var i = 0; i < items.length; i++) {
                                var item = items[i];
                                sum += parseFloat(item.summary_amount);
                            }
                        }

                        return sum;
                    };

                    //新建发票摘要
                    $dialogScope.newInvoiceAbstract = function() {
                        var items = $dialogScope.invoiceInfo.invoiceSummarys;
                        var id;
                        id = items.length ? items[0].id + 1 : 1;
                        var summary = {
                            id: id,
                            summary_type: '软件技术服务费',
                            summary_amount: '0'
                        };
                        items.unshift(summary);
                    };

                    //删除发票摘要
                    $dialogScope.removeInvoiceAbstract = function(idx) {
                        var item;
                        var items = $dialogScope.invoiceInfo.invoiceSummarys;
                        items.splice(idx, 1);
                    };

                    $dialogScope.vaildSummaryRequired = function() {
                        var items = $dialogScope.invoiceInfo.invoiceSummarys || [];
                        if (items.length === 0) {
                            return true;
                        }
                        var rst = $.grep(items, function(d, i) {
                            return d.summary_amount == null;
                        });
                        return rst.length > 0;
                    };
                    $dialogScope.vaildSummaryNumber = function() {
                        var items = $dialogScope.invoiceInfo.invoiceSummarys;
                        var rst = $.grep(items, function(d, i) {
                            return d.summary_amount && !d.summary_amount.toString().match(/^-?[\d]*(\.[\d]+)*$/);
                        });
                        return rst.length > 0;
                    };

                    var self = this;
                    $dialogScope.showInvoiceImport = function() {
                        $dialogScope.query = {
                            keyword: '',
                            execute() {
                                contractCommonService.getCanUseInvoiceInfo($dialogScope.invoiceInfo.contract_id,
                                    $dialogScope.query.keyword, function(data) {
                                        $dialogScope.importInvoices = data;
                                        $dialogScope.$applyAsync();
                                    });
                            }
                        };
                        self.onInvoiceImportShow($dialogScope, '引入未关联合同发票', $dialogScope.importInvoice);
                    };
                    $dialogScope.importInvoice = function(item) {
                        $dialogScope.invoiceInfo = angular.extend($dialogScope.invoiceInfo, angular.copy(item),
                            {contract_id: $dialogScope.invoiceInfo.contract_id});
                        $dialogScope.$applyAsync();

                        setTimeout(function() {
                            $('.idProposer:visible').length && $('.idProposer:visible').
                                data('select2').
                                updateSelection({text: $dialogScope.invoiceInfo.UserName});
                            $('.idInvoiceCompany:visible').length && $('.idInvoiceCompany:visible').
                                data('select2').
                                updateSelection({text: $dialogScope.invoiceInfo.BUName});
                            $('.idMainInvoice:visible').length && $('.idMainInvoice:visible').
                                data('select2').
                                updateSelection({text: $dialogScope.invoiceInfo.main_invoice_no});
                        }, 100);
                    };

                    //附件上传初始化
                    setTimeout(function() {
                        $('#fileupload').fileupload({
                            dataType: 'json',
                            url: api_prefix + '/common/file/upload-document',
                            add(e, data) {
                                // 大小限制
                                if (data.files.length > 0) {
                                    if (data.files[0].size > config.uploader.max_file_size) {
                                        util.alert('文件大小超出' + config.uploader.max_file_size_text + '，无法上传。');
                                        return;
                                    }
                                }
                                data.submit();
                                ui.loading('', '正在上传…');
                            },
                            done(e, data) {
                                var res = data.result;
                                if (res.retCode == '0') {
                                    var attachement = {
                                        __type: 'add',
                                        document_id: data._time,
                                        document_name: data.files[0].name,
                                        document_ext_name: '',
                                        document_path: res.data.path
                                    };
                                    $dialogScope.invoiceInfo.invoiceDocuments.push(attachement);
                                    $dialogScope.$applyAsync();
                                    ui.removeLoading();

                                    $('#fileupload_error').html('');
                                    $('#fileupload_error').hide();
                                } else {
                                    ui.removeLoading();
                                    $('#fileupload_error').html('上传失败:' + res.errMsg);
                                    $('#fileupload_error').show();
                                }
                            },
                            fail(e, data) {
                                $('#fileupload_error').html('上传失败:' + data.errorThrown);
                                $('#fileupload_error').show();
                                ui.removeLoading();
                            },
                            always(e, data) {
                                ui.removeLoading();
                            }
                        });
                    }, 0);

                    /**
                     * 删除附件
                     * @param data
                     * @param id
                     */
                    $dialogScope.delAttachment = function(item, idx) {
                        if (item.__type == 'add') {
                            $dialogScope.invoiceInfo.invoiceDocuments.splice(idx, 1);
                        } else {
                            angular.extend(item, {__type: 'delete'});
                        }
                        $dialogScope.$applyAsync();
                    };

                },
                onInvoiceImportShow($dialogScope, title, callback) {
                    /**
                     * 引入未关联合同界面初始化
                     */

                    $dialogScope.importInvoices = [];

                    $dialogScope.query.execute();

                    $dialogScope.selectInvoice = function(item) {
                        $.each($dialogScope.importInvoices, function(i, d) {
                            d.__selected = false;
                        });
                        item.__selected = true;
                    };

                    var d = dialog({
                        title: title,
                        content: $('.importInvoiceDlg:last'),
                        fixed: true,
                        width: 650,
                        height: 450,
                        okValue: '确定',
                        ok() {
                            var selectedInvoices = $.grep($dialogScope.importInvoices, function(d, i) {
                                return d.__selected == true;
                            });
                            if (selectedInvoices.length) {
                                if (callback && typeof callback == 'function') {
                                    callback(selectedInvoices[0]);
                                    $dialogScope.$applyAsync();
                                }
                            } else {
                                util.alert('请选择发票记录');
                                return false;
                            }

                            return true;
                        },
                        cancel() {
                        }
                    });
                    d.showModal();

                },
                editInvoiceSave($data, $dialog, $dialogScope, callback, contract, isAdd) {
                    /**
                     * 保存新增发票
                     * isAdd 1: 发票,收据新增,红冲发票
                     *       0 :  编辑 发票,收据
                     */

                        //客户名称不等于签约客户全称时提示发票名称与签约客户全称不一致.
                        //云客签约-直属区域 : 7f83719a-fce8-11e4-bed8-00155d02c832
                        //云客签约-联营区域 : 7f8422d0-fce8-11e4-bed8-00155d02c832
                        //云客直销 : efa353cd-51ca-11e8-a035-00155d02c83e
                    var yunkeArr = ['7f83719a-fce8-11e4-bed8-00155d02c832', '7f8422d0-fce8-11e4-bed8-00155d02c832', 'efa353cd-51ca-11e8-a035-00155d02c83e'];

                    //联营签约-云客区域: 7f856e81-fce8-11e4-bed8-00155d02c832
                    //客户名称不等于合同签署公司时提示发票名称与签约客户全称不一致，是否继续提交
                    var lianyingContract = '7f856e81-fce8-11e4-bed8-00155d02c832';

                    var customerIsValid = false,
                        customerNotValidTips = '';

                    if (contract.contract_property_id == yunkeArr[0] || contract.contract_property_id == yunkeArr[1] || contract.contract_property_id == yunkeArr[2]) {
                        if ($dialogScope.invoiceInfo.customer_name != contract.customer_full_name) {
                            customerIsValid = true;
                            customerNotValidTips = '发票名称与签约客户全称不一致，是否继续提交?';
                        }

                    }

                    if (contract.contract_property_id == lianyingContract) {
                        if ($dialogScope.invoiceInfo.customer_name != contract.company_name) {
                            customerIsValid = true;
                            customerNotValidTips = '发票名称与合同签署公司不一致，是否继续提交';
                        }
                    }

                    var invoiceInfo = $dialogScope.invoiceInfo;
                    var checkedReceivables = $.grep($dialogScope.editInvoiceReceivables || [], function(d, i) {
                        return d._checked == true;
                    });

                    //红冲此发票不需要弹出选项
                    if (!$dialogScope.data.isHongChongInvoice) {
                        if (checkedReceivables.length <= 0) {
                            util.alert('请至少勾选一条应收信息');
                            return false;
                        }
                    }

                    invoiceInfo.invoiceReceivables = checkedReceivables;

                    //校验
                    if ($('.error:visible').length) {
                        return false;
                    }

                    if (customerIsValid && isAdd == 1) {
                        util.confirm(customerNotValidTips, {
                            ok() {
                                service.cofirmSaveInvoice($dialog, invoiceInfo, callback, {
                                    isHongChongInvoice: $dialogScope.data.isHongChongInvoice
                                });
                            }
                        });
                    } else {
                        service.cofirmSaveInvoice($dialog, invoiceInfo, callback, {
                            isHongChongInvoice: $dialogScope.data.isHongChongInvoice
                        });
                    }

                    return false;

                },
                cofirmSaveInvoice($dialog, invoiceInfo, callback, options) {
                    var post_data = invoiceInfo;
                    var url;
                    url = api_prefix + '/receivable/save-invoice-receivable';
                    //如果是红冲发票，用这个接口
                    if (options.isHongChongInvoice) {
                        url = api_prefix + '/invoice/save-invoice';
                    }
                    util.myAjax({
                        url: url,
                        type: 'POST',
                        context: this,
                        data: post_data,
                        async: false,
                        success(json) {
                            if (json.retCode == 0) {
                                util.alert('保存成功');
                                if (callback) {
                                    callback();
                                }
                                $dialog.close();
                            } else {
                                util.alert('保存失败：' + json.errMsg);
                                return false;
                            }
                        }
                    });
                },
                beforeUnbindPaymentForInvoice($dialog, $dialogScope, record) {

                    _.extend($dialogScope, _.pick(record, 'invoice_code', 'invoice_date'));

                    util.myAjax({
                        url: api_prefix + '/receivable/get-payment-list-by-invoice-id',
                        type: 'GET',
                        context: this,
                        data: _.pick(record, 'invoice_id'),
                        async: false,
                        success(json) {
                            $dialogScope.data = json.data || [];
                            $dialogScope.$applyAsync();
                        }
                    });

                },
                unbindPaymentForInvoice(data, callback) {
                    util.myAjax({
                        url: api_prefix + '/receivable/un-bind-payment-for-invoice',
                        type: 'POST',
                        context: this,
                        data: {payment_ids: _(data).filter(x => !!x['_checked']).map('payment_id').value()},
                        async: false,
                        success(json) {
                            if (json.retCode == 0) {
                                util.alert('解除成功');
                                if (callback) {
                                    callback();
                                }
                            } else {
                                util.alert('解除失败：' + json.errMsg);
                                return false;
                            }
                        }
                    });
                },
                deleteInvoice(invoiceInfo, callback) {
                    /**
                     * 删除发票
                     */
                    util.confirm('确定要删除此发票吗?', {
                        ok() {
                            var post_data = {invoice_id: invoiceInfo.invoice_id};
                            var url;
                            url = api_prefix + '/receivable/delete-invoice';

                            util.myAjax({
                                url: url,
                                type: 'POST',
                                context: this,
                                data: post_data,
                                success(json) {
                                    if (json.retCode == 0) {
                                        invoiceInfo.__isdelete = 1;
                                        util.alert('删除成功');
                                        $rootScope.$applyAsync();
                                        if (callback) {
                                            callback();
                                        }
                                    } else {
                                        util.alert('删除失败：' + json.errMsg);
                                    }
                                }
                            });
                        }
                    });
                },
                convertToInvoice(invoiceInfo, $event) {
                    /**
                     * 收据转为发票
                     */
                    util.confirm('确定要把此收据转为发票吗?', {
                        ok() {
                            var post_data = angular.extend({}, invoiceInfo, {is_receipt: 0});
                            var url;
                            url = api_prefix + '/receivable/save-invoice-receivable';

                            util.myAjax({
                                url: url,
                                type: 'POST',
                                context: this,
                                data: post_data,
                                success(json) {
                                    if (json.retCode == 0) {
                                        util.alert('收据转为发票成功', {
                                            ok() {
                                                $event && $($event.target).parent().find('[type=edit]').map((key,dom)=>{
                                                    dom.click();
                                                });
                                                invoiceInfo.is_receipt = 0;
                                                $rootScope.$applyAsync();
                                            }
                                        });
                                    } else {
                                        util.alert('收据转为发票失败：' + json.errMsg);
                                    }
                                }
                            });
                        }
                    });
                }
            };
            return service;
        }]);

    module.exports = ContractReceivableInvoice;
});
